package com.gitee.hljdrl.utils.os;


import android.content.Context;


import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态获取BuildConfig字段到Map中
 *
 */
public class BuildConfigUtil {

    public static Map<String, Object> forValue(Class clazz) {
        Map<String, Object> map = new HashMap(16);
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            Class<?> type = field.getType();
            Object value = null;
            try {
                value = field.get(type);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            map.put(field.getName(), value);
        }
        return map;
    }

    public static Object getBuildConfigValue(Context ctx, String key) {
        try {
            Class<?> clazz = Class.forName(ctx.getClass().getPackage().getName() + ".BuildConfig");
            Field field = clazz.getField(key);
            return field.get(null);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, Object> getBuildConfigForMap(String packageName) {
        try {
            Class<?> clazz = Class.forName(packageName + ".BuildConfig");
            return forValue(clazz);
        } catch (ClassNotFoundException e) {
//            L.d("BuildConfigUtil", "Unable to get the BuildConfig, is this built with ANT?");
            e.printStackTrace();
        } catch (NullPointerException e) {
//            L.d("BuildConfigUtil", "Null Pointer Exception: Let's print a stack trace.");
            e.printStackTrace();
        }
        return new HashMap<>();
    }
}
